package com.turtledove.storyalbum.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.turtledove.storyalbum.R;
import com.turtledove.storyalbum.common.ConstCommon;
import com.turtledove.storyalbum.common.UtilsCommon;
import com.turtledove.storyalbum.model.adapter.AdapterFacebook;
import com.turtledove.storyalbum.model.delegate.ServiceDelegate;
import com.turtledove.storyalbum.model.helper.DBHandler;
import com.turtledove.storyalbum.model.object.ObjectFacebookImage;
import com.turtledove.storyalbum.model.object.ObjectImage;

public class FacebookImageAddActivity extends Activity implements
		OnClickListener {

	GridView gridContent;
	AdapterFacebook adapter;
	TextView txtItemSelected, txtDone;
	ArrayList<ObjectFacebookImage> arrayImage, arrayImageSelected;
	ArrayList<ObjectImage> arrayImageClient;
	Dialog dialog;//, dialogDownload;
	Context mContext;
	String idAlbum;
	String access_token;
	String urlFolder;
	ViewFlipper vf;
	int LOADING = 0, CONTENT = 1, ERRO = 2;

	// ____________________ System Function _____________________________

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_facebook);
		initWidget();
		initDB();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.txtDone:
			showDialogAlbum();
			break;
		default:
			break;
		}

	}

	// ________________________ Custom Function ______________

	// download file
	public void downloadFile(final int maxIdAlbum) {
		try {
//			dialogDownload = ProgressDialog.show(this, "",
//					getString(R.string.downloading_file), true);

			final String urlFolder = UtilsCommon
					.createFolder(getString(R.string.facebook));
			new Thread(new Runnable() {
				public void run() {
					for (int i = 0; i < arrayImageSelected.size(); i++) {
						ObjectFacebookImage mObjectFacebookImage = arrayImageSelected
								.get(i);
						String urlDownload = mObjectFacebookImage
								.getImage_source();
						boolean checkStatus = UtilsCommon.downLoadFile(
								FacebookImageAddActivity.this, urlDownload,
								urlFolder);
						if (checkStatus != false) {
							Log.d("Luong",
									"************************ download image: "
											+ mObjectFacebookImage
													.getImage_source());
							String itemCover = "0";
							if (i == 0) {
								itemCover = "1";
							}
							ObjectImage mObjectImage = new ObjectImage();
							mObjectImage.setUrlImage(urlFolder
									+ "/"
									+ urlDownload.substring(urlDownload
											.lastIndexOf("/")));
							arrayImageClient.add(mObjectImage);
							DBHandler.insertItem(mContext,
									mObjectImage.getUrlImage(),
									String.valueOf(maxIdAlbum), itemCover);
						} else {
							Log.e("Luong",
									"************************ download image fail: "
											+ mObjectFacebookImage
													.getImage_source());
						}
					}
//					dialogDownload.dismiss();
				}
			}).start();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private void initWidget() {
		vf = (ViewFlipper) findViewById(R.id.vf);
		vf.setDisplayedChild(LOADING);
		arrayImage = new ArrayList<ObjectFacebookImage>();
		arrayImageClient = new ArrayList<ObjectImage>();
		mContext = this;
		txtItemSelected = (TextView) findViewById(R.id.txtItemSelected);
		txtItemSelected.setOnClickListener(this);
		txtDone = (TextView) findViewById(R.id.txtDone);
		txtDone.setOnClickListener(this);
	}

	private void initDB() {
		Intent intent = new Intent();
		intent = getIntent();
		idAlbum = intent.getExtras().getString(ConstCommon.KEY_RESULT_ID_ALBUM);
		access_token = intent.getExtras().getString(
				ServiceDelegate.KEY_ACCESS_TOKEN);
		ServiceDelegate.getFacebookImage(mhandlerImage, access_token, idAlbum);
	}

	public ArrayList<ObjectFacebookImage> getListImageSelected() {
		ArrayList<ObjectFacebookImage> listImageSelected = new ArrayList<ObjectFacebookImage>();
		try {
			if (arrayImage.size() > 0) {
				for (int i = 0; i < arrayImage.size(); i++) {
					if (arrayImage.get(i).isSelected()) {
						listImageSelected.add(arrayImage.get(i));
					}
				}
			}
			txtItemSelected.setText(listImageSelected.size() + " "
					+ getResources().getString(R.string.selected));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listImageSelected;
	}

	void showDialogAlbum() {
		try {
			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.change_album));
			dialog.setContentView(R.layout.dialog_album_info);
			final EditText dialogNameAlbum = (EditText) dialog
					.findViewById(R.id.dialogNameAlbum);
			final CheckBox cbCurrentAlbum = (CheckBox) dialog
					.findViewById(R.id.cbCurrentAlbum);
			Button dialog_BtnYes = (Button) dialog.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog.findViewById(R.id.dialog_BtnNo);
			dialog_BtnYes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					String currentAlbum = "0";
					if (cbCurrentAlbum.isChecked()) {
						currentAlbum = "1";
						DBHandler.disableCurrentAlbum(mContext);
					}
					// insert album
					DBHandler.insertAlbum(mContext, dialogNameAlbum.getText()
							.toString().trim(), currentAlbum);

					// insert item of album
					int maxIdAlbum = DBHandler.getMaxIdAlbum(mContext);
					if (maxIdAlbum > 0) {
						arrayImageSelected = getListImageSelected();
						if (arrayImageSelected.size() > 0) {
							arrayImageClient = new ArrayList<ObjectImage>();
							// File f = new
							// File(UtilsCommon.createFolder(getString(R.string.facebook)));
							// urlFolder = f.toString();
							// UtilsCommon.deleteFile(f);
							downloadFile(maxIdAlbum);

						}
					}
					// change status service widget
					WidgetUpdateService.statusCurrentAlbum = true;
					dialog.dismiss();
					updateListImage(maxIdAlbum);
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void updateListImage(int idAlbum) {
		Intent returnIntent = new Intent();
		Log.d("Luong", "Luong_______________________ idAlbum: " + idAlbum);
		returnIntent.putExtra(ConstCommon.KEY_RESULT_ID_ALBUM, idAlbum);
		setResult(RESULT_OK, returnIntent);
		finish();
	}

	Handler mhandlerImage = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					JSONArray dataJSONArray = new JSONArray();
					dataJSONArray = dataJSONObject
							.getJSONArray(ServiceDelegate.KEY_DATA);
					Log.d("Luong",
							"Luong_____________________________ dataJSONArray: "
									+ dataJSONArray);
					int totalImage = dataJSONArray.length();
					if (totalImage > 0) {
						for (int i = 0; i < totalImage; i++) {
							JSONObject imageJSONObject = new JSONObject();
							imageJSONObject = dataJSONArray.getJSONObject(i);

							ObjectFacebookImage mObjectFacebookImage = new ObjectFacebookImage();
							mObjectFacebookImage.setImage_id(imageJSONObject
									.getString(ServiceDelegate.KEY_ID));

							JSONArray imageJSONArray = new JSONArray();
							imageJSONArray = imageJSONObject
									.getJSONArray(ServiceDelegate.KEY_IMAGE);
							if (imageJSONArray.length() > 0) {
								for (int j = 0; j < imageJSONArray.length(); j++) {
									float imageHeigh = (float) imageJSONArray
											.getJSONObject(j).getDouble(
													ServiceDelegate.KEY_HEIGHT);
									float imageWidth = (float) imageJSONArray
											.getJSONObject(j).getDouble(
													ServiceDelegate.KEY_WIDTH);
									Point sizeScreen = UtilsCommon
											.getSizeScreen(FacebookImageAddActivity.this);
									if (imageHeigh <= sizeScreen.y
											&& imageWidth <= sizeScreen.x)
										;
									{
										mObjectFacebookImage
												.setImage_source(imageJSONArray
														.getJSONObject(j)
														.getString(
																ServiceDelegate.KEY_SOURCE));
										mObjectFacebookImage
												.setImage_height(imageHeigh);
										mObjectFacebookImage
												.setImage_width(imageWidth);
										break;
									}
								}
							}
							arrayImage.add(mObjectFacebookImage);
						}
						if (arrayImage.size() > 0) {
							Log.d("Luong",
									"Luong_______________________ total img: "
											+ arrayImage.size());
							vf.setDisplayedChild(CONTENT);
							adapter = new AdapterFacebook(
									FacebookImageAddActivity.this, arrayImage);
							gridContent = (GridView) findViewById(R.id.gridContent);
							gridContent.setFastScrollEnabled(true);
							gridContent.setAdapter(adapter);
						} else {
							vf.setDisplayedChild(ERRO);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	};
}